package com.zt.rongda.order.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zt.rongda.constant.BusConstant;
import com.zt.rongda.order.inter.OrderItemMapper;
import com.zt.rongda.order.inter.OrderMapper;
import com.zt.rongda.order.model.Order;
import com.zt.rongda.order.model.OrderItem;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.DateUtil;
import com.zt.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class OrderService extends BaseService {

    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;

    /**
    * 查询
    *
    * @param reqBean
    * @return
    */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("select a.*,c.CUSTOMER_NAME from AD_ORDER a " +
                "left join CUSTOMER c on c.CUSTOMER_ID = a.CUSTOMER_ID where 1=1 ");
        sqlBuilder.addWhere("ORDER_ID", reqBean.getInfo("orderId"));
        sqlBuilder.addWhere("CUSTOMER_ID", reqBean.getInfo("customerId"));
        sqlBuilder.addWhere("STATUS", reqBean.getInfo("status"));
        sqlBuilder.addWhere("C_ORDER_TYPE", reqBean.getInfo("orderType"));
        sqlBuilder.orderBy("order by a.MAKE_TIME DESC");
        JSONObject result = queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
        JSONArray rows = result.optJSONArray("rows");
        if(rows != null && !rows.isEmpty()){
            for(Object o : rows){
                JSONObject order = (JSONObject)o;    
                order.put("orderItems", getOrderItems(order.optString("orderId")));
            }
        }
        return result;
    }

    /**
    * 通过id查询
    *
    * @param orderId
    * @return
    */
    public JSONObject getById(String orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        JSONObject orderObj = null;
        if(order != null){
            orderObj = order.toJSONObject();
            orderObj.put("orderItems", getOrderItems(orderId));
        }
        return orderObj;
    }
    
    private JSONArray getOrderItems(String orderId){
        SqlBuilder sqlBuilder = new SqlBuilder("select i.* ");
        sqlBuilder.appendSql(" ,e1.EMP_NAME caituEmpName,e2.EMP_NAME printEmpName,e3.EMP_NAME fumoEmpName ");
        sqlBuilder.appendSql(" from AD_ORDER_ITEM i ");
        sqlBuilder.appendSql(" left join EMPLOYEE e1 on i.CAITU_EMP_ID = e1.EMP_ID");
        sqlBuilder.appendSql(" left join EMPLOYEE e2 on i.PRINT_EMP_ID = e2.EMP_ID");
        sqlBuilder.appendSql(" left join EMPLOYEE e3 on i.FUMO_EMP_ID = e3.EMP_ID");
        sqlBuilder.appendSql(" where i.ORDER_ID = ?", orderId);
        sqlBuilder.orderBy(" order by i.MAKE_TIME ");
        return query(sqlBuilder);
    }

    /**
    * 新增
    *
    * @param order
    */
    public void add(Order order,ReqBean reqBean) {
        order.setOrderId(stringId());// 手动设置Id
        
        order.setRecordUserId(reqBean.getUserId());
        order.setRecordTime(new Date());
        order.setStatus(BusConstant.OrderStatus.UN_FINISH);
        order.setMakeTime(new Date());
        order.setModifyTime(order.getMakeTime());
        orderMapper.insert(order);
        
        String orderItemsStr = reqBean.getInfo("orderItems");
        if(StringUtil.isNotEmpty(orderItemsStr)){
            JSONArray orderItems = JSONArray.fromObject(orderItemsStr);
            if(orderItems != null){
                for(Object o : orderItems){
                    JSONObject orderItem = (JSONObject)o;
                    OrderItem item = new OrderItem();
                    item.setOrderItemId(stringId());
                    item.setOrderId(order.getOrderId());
                    
                    item.setBusId(orderItem.optString("busId"));
                    item.setBusCompany(orderItem.optString("busCompany"));
                    item.setBusLineName(orderItem.optString("busLineName"));
                    item.setBusPlateNo(orderItem.optString("busPlateNo"));
                    item.setBusVehicleNo(orderItem.optString("busVehicleNo"));
                    item.setBusVehicleNoAbbr(orderItem.optString("busVehicleNoAbbr"));
                    item.setBusType(orderItem.optString("busType"));
                    
                    item.setAdName(orderItem.optString("adName"));
                    item.setPublishType(orderItem.optString("publishType"));
                    item.setPublishDate(DateUtil.parse(orderItem.optString("publishDate")));
                    item.setPublishCycle(orderItem.optString("publishCycle"));
                    
                    item.setOperator(reqBean.getUserId());
                    item.setMakeTime(new Date());
                    item.setModifyTime(new Date());
                    orderItemMapper.insert(item);
                }
            }
        }
    }

    /**
    * 修改
    *
    * @param order
    */
    public void update(Order order,ReqBean reqBean) {
        String orderId = order.getOrderId();
        if (StringUtil.isEmpty(orderId)) {
            throw new BusinessException("获取主键失败");
        }

        order.setModifyTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
        
        String orderItemsStr = reqBean.getInfo("orderItems");
        if(StringUtil.isNotEmpty(orderItemsStr)){
            JSONArray orderItems = JSONArray.fromObject(orderItemsStr);
            if(orderItems != null){
                for(Object o : orderItems){
                    JSONObject orderItem = (JSONObject)o;
                    OrderItem item = new OrderItem();
                    
                    item.setOrderId(order.getOrderId());
                    item.setBusId(orderItem.optString("busId"));//TODO 如busId为空,根据车牌号或自编号匹配车辆,未匹配则增加车辆
                    item.setBusCompany(orderItem.optString("busCompany"));
                    item.setBusLineName(orderItem.optString("busLineName"));
                    item.setBusPlateNo(orderItem.optString("busPlateNo"));
                    item.setBusVehicleNo(orderItem.optString("busVehicleNo"));
                    item.setBusVehicleNoAbbr(orderItem.optString("busVehicleNoAbbr"));
                    item.setBusType(orderItem.optString("busType"));
                    
                    item.setAdName(orderItem.optString("adName"));
                    item.setPublishType(orderItem.optString("publishType"));
                    item.setPublishDate(DateUtil.parse(orderItem.optString("publishDate")));
                    item.setPublishCycle(orderItem.optString("publishCycle"));
                    
                    String orderItemId = orderItem.optString("orderItemId", "");
                    if(StringUtil.isNotEmpty(orderItemId)){
                        item.setOrderItemId(orderItemId);
                        item.setModifyTime(order.getModifyTime());
                        orderItemMapper.updateByPrimaryKeySelective(item);
                    }else{
                        item.setOrderItemId(stringId());
                        item.setOperator(reqBean.getUserId());
                        item.setMakeTime(order.getModifyTime());
                        item.setModifyTime(order.getModifyTime()); 
                        orderItemMapper.insert(item);
                    }
                }
            }
        }
    }

    /**
    * 删除
    *
    * @param orderId
    */
    public void delete(String orderId) {
        if (StringUtil.isEmpty(orderId)) {
            throw new BusinessException("获取主键失败");
        }
        //TODO 判断制作单是否可删除
        orderItemMapper.deleteByOrderId(orderId);
        orderMapper.deleteByPrimaryKey(orderId);
    }
    
    /**
     * 删除
     *
     * @param orderItemId
     */
     public void deleteItem(String orderItemId) {
         if (StringUtil.isEmpty(orderItemId)) {
             throw new BusinessException("获取主键失败");
         }
         //TODO 判断制作单明细是否可删除
         orderItemMapper.deleteByPrimaryKey(orderItemId);
     }

     /**
      * 根据状态查询制作单
      * @param orderStatus
      * @return
      */
     public List<Order> getOrderByStatus(String orderStatus){
    	 return orderMapper.selectByStatus(orderStatus);
     }
     
     /**
      * 根据工作单明细id查询制作单明细
      * @param workBillItemId
      * @return
      */
     public OrderItem getOrderItemByWorkBillItemId(String workBillItemId){
    	return orderItemMapper.selectByWorkBillItemId(workBillItemId);
     }
}